﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;

public partial class Site_Download : xIx.Web.UI.PageBase
{
    private string mdbFile;
    private string datayear;
    private string dataProvince;
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    private void CreateDownloadFile()
    {
        datayear = Request["Y"];
        dataProvince = Request["p"];
        mdbFile = string.Format("..\\UserFiles\\{0}_{1}.csv", Request["p"], Request["Y"]);
        string root = AppDomain.CurrentDomain.BaseDirectory + "\\Site";
        string tempFile = Path.Combine(root, mdbFile);
        if (!File.Exists(tempFile))
        {
            if (string.IsNullOrWhiteSpace(Request["Y"]) || string.IsNullOrWhiteSpace(Request["P"]))
            {
                Response.Write("ERROR.");
                return;
            }
            var dbName = System.Configuration.ConfigurationManager.AppSettings["dedorm"];
            if (string.IsNullOrEmpty(dbName))
            {
                return;
            }
            var dbConn = System.Configuration.ConfigurationManager.ConnectionStrings[dbName];
            if (dbConn == null)
            {
                return;
            }
            string dbpath = string.Empty;
            if (dbConn.ConnectionString.Contains("[AppRoot]"))
            {
                int start = dbConn.ConnectionString.IndexOf("[AppRoot]") + "[AppRoot]".Length;
                dbpath = "~" + dbConn.ConnectionString.Substring(start).Replace("\\", "/");
            }
            mdbFile = dbpath;
            System.Data.DataTable dt = new System.Data.DataTable();
            //downloadLink.NavigateUrl = dbpath;
            using (xIx.Data.DbHelper dh = new xIx.Data.DbHelper("dedorm", null))
            {
                if (Request["Y"] == "全部")
                {
                    dt = dh.Table[Request["P"]].Select();
                }
                else
                {
                    int year = 0;
                    year = int.Parse(Request["Y"]);
                    dt = dh.Table[Request["P"]].Where("date>=@Start and date<@End").Select((year * 10000), ((year + 1) * 10000));
                }
            }
            ConvertDataTableToCSV(tempFile, dt);
        }
    }

    private static void ConvertDataTableToCSV(string tempFile, System.Data.DataTable dt)
    {
        List<string> allLine = new List<string>();
        StringBuilder header = new StringBuilder();
        foreach (System.Data.DataColumn column in dt.Columns)
        {
            header.Append(column.ColumnName + ",");
        }
        header.Remove(header.Length - 1, 1);
        allLine.Add(header.ToString());
        foreach (System.Data.DataRow row in dt.Rows)
        {
            var valueList = row.ItemArray;
            StringBuilder sb = new StringBuilder();
            foreach (object o in valueList)
            {
                sb.Append(o + ",");
            }
            sb.Remove(sb.Length - 1, 1);
            allLine.Add(sb.ToString());
        }
        System.IO.File.AppendAllLines(tempFile, allLine, Encoding.UTF8);
    }

    protected void downloadLink_Click(object sender, EventArgs e)
    {
        datayear = Request["Y"];
        dataProvince = Request["p"];
        string cmd = string.Format("Insert into DownLoadRecord (CustomeType,Name,Purpose,DownloadTime,DataTime,Province)"
            + " Values(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\")", ddlType.SelectedValue, tbxName.Text, Description.InnerText, 
            DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),datayear,dataProvince );
        using (xIx.Data.DbHelper dh = new xIx.Data.DbHelper("ConnSet", null))
        {
            dh.Exec(cmd);
        }

        CreateDownloadFile();
        string name = mdbFile;// Request["url"];
        int k = name.LastIndexOf("/");
        string filename = name.Remove(0, k + 1);

        string filePath = Server.MapPath(name);//路径

        //以字符流的形式下载文件 
        System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0, bytes.Length);
        fs.Close();
        Response.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开 
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
        Response.Write("<script language:javascript>javascript:window.opener=null;window.close();</script>");

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Write("<script language:javascript>javascript:window.opener=null;window.close();</script>");
    }
}